package com.ithuameng.admin.utils;

import com.ithuameng.admin.app.system.model.AdminLoginUser;
import com.ithuameng.admin.enums.CommonError;
import com.ithuameng.admin.exception.AdminException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

@Slf4j
public class SecurityUtils {

	/**
	 * 获取登录用户
	 * 
	 * @return
	 */
	public static AdminLoginUser getLoginUser() {
		try {
			return (AdminLoginUser) getAuthentication().getPrincipal();
		} catch (Exception e) {
			throw new AdminException(CommonError.UNAUTHORIZED);
		}
	}

	/**
	 * 获取Authentication
	 * 
	 * @return
	 */
	public static Authentication getAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}

	public static String getUsername() {
		try {
			return getLoginUser().getUsername();
		} catch (Exception e) {
			log.error("Failed to get username", e);
		}
		return "sys";
	}
	
	public static Long getUserId() {
		try {
			return getLoginUser().getId();
		} catch (Exception e) {
			log.error("Failed to get username", e);
		}
		return null;
	}
}
